﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ScriptEditor.Commands;
using System.Reflection;

namespace ScriptEditor
{
    /// <summary>
    /// Editor.xaml 的交互逻辑
    /// </summary>
    public partial class Editor : Window
    {
        Dictionary<string, CommandUI> thisUI = new Dictionary<string, CommandUI>();
        Script thisScripts = null;
        int thisIndex = 0;
        public Editor()
        {
            InitializeComponent();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            Hide();
        }

        public void SetCommandUI(Dictionary<string, CommandUI> uis, Script commands, int index)
        {
            //初始化编辑窗口
            UIBox.Children.Clear();
            UIBox.RowDefinitions.Clear();
            UIBox.Height = SubmitBox.Height;
            thisUI = uis;
            thisScripts = commands;
            thisIndex = index;

            //载入对应指令UI
            int i = 0;
            foreach (KeyValuePair<string, CommandUI> pair in uis)
            {
                UIBox.Height += CommandUI.cell * pair.Value.size;
                RowDefinition row = new RowDefinition();
                row.Height = new GridLength(pair.Value.size, GridUnitType.Star);
                UIBox.RowDefinitions.Add(row);
                UIBox.Children.Add(pair.Value);
                Grid.SetRow(pair.Value, i);
                i++;
            }
        }

        private void Submit_Click(object sender, RoutedEventArgs e)
        {
            Command command = thisScripts[thisIndex];
            Dictionary<string, object> valueRec = new Dictionary<string, object>();
            PropertyInfo[] infos = command.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo info in infos)
            {
                bool success = true;
                valueRec.Add(info.Name, thisUI[info.Name].GetValue(out success));
                if (!success)
                {
                    MessageBox.Show(info.Name + "输入的数据不合法");
                    return;
                }
            }
            foreach (PropertyInfo info in infos)
            {
                info.SetValue(command, valueRec[info.Name], null);
            }
            thisScripts[thisIndex] = (Command)command.ConvertCommand();
        }
    }
}
